package com.base.look.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.utils.GlideUtil;
import com.base.commonlib.utils.SubStringUtil;
import com.base.commonlib.widget.OvalImageView;
import com.base.look.R;
import com.base.look.act.LookBigImagesActivity;
import com.base.look.bean.CommentModel;
import com.base.look.bean.ImageUrl;
import com.base.look.bean.LookListBean;
import com.base.look.lookwidget.CommentTextView;
import com.base.look.lookwidget.LookControlPanel;
import com.base.look.lookwidget.TextBlankClickListener;
import com.base.look.utils.MediaUtils;
import com.base.look.utils.TimeUtils;
import com.base.look.widget.MultiImageView;
import com.base.video.java.VideoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zw on 2020/3/2.
 * 看看列表适配器xxxx
 */

@SuppressWarnings("all")
public class LookExamineAdapter extends RecyclerView.Adapter<LookExamineAdapter.ViewHolder> {
    private Context mContext;
    private OnActionListener mOnActionListener;
    private List<LookListBean.Rows> mData;
    private String mUserId;

    public LookExamineAdapter(Context mContext, List<LookListBean.Rows> mData, String userId) {
        this.mContext = mContext;
        this.mData = mData;
        this.mUserId = userId;
    }

    public void setOnActionListener(OnActionListener listener) {
        mOnActionListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_examine_video_comment_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final LookListBean.Rows rows = mData.get(position);
        holder.icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onUserIconClick(rows.getPublisher());
            }
        });

        holder.name.setText(rows.getPublisher());
        try {
            holder.time.setText(TimeUtils.format(rows.getPublishTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        holder.commentCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onComment(rows, position);
            }
        });

        holder.zanCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null) {
                    mOnActionListener.onHit(rows, position);
                }
            }
        });

        holder.view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onLongClick(rows);
                return true;
            }
        });
        holder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null) {
                    mOnActionListener.onDeleteLookClick(rows.getId(),position);
                }
            }
        });
        refreshItemView(holder, rows, position);
    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            //局部刷新，
            Object object = payloads.get(0);
            if (object instanceof CommentModel) {
                refreshItemView(holder, mData.get(position), position);

            }
        }
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    private void refreshItemView(final ViewHolder holder, final LookListBean.Rows rows, final int position) {
        //得到drawable对象，即所要插入的图片
//        Drawable d;
//        if (rows.getThumbIdList().size() > 0) {
//            for (int i = 0; i < rows.getThumbIdList().size(); i++) {
//                if (rows.getThumbIdList().toString().contains(mUserId)) {
//                    rows.setHit(true);
//                } else {
//                    rows.setHit(false);
//                }
//            }
//        }
//        if (rows.isHit()) {
//            d = mContext.getResources().getDrawable(R.mipmap.icon_zan);
//        } else {
//            d = mContext.getResources().getDrawable(R.mipmap.icon_un_zan);
//        }
//        holder.zanCount.setCompoundDrawablesWithIntrinsicBounds(d,
//                null, null, null);
        holder.zanCount.setCompoundDrawablePadding(mContext.getResources().getDimensionPixelOffset(R.dimen.dp_4));

        if (rows.getComments().size() > 0 || rows.getThumbList().size() > 0) {
            holder.item_thumbs_lin.setVisibility(View.VISIBLE);
        } else {
            holder.item_thumbs_lin.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(rows.getAddress())) {
            holder.address.setVisibility(View.GONE);
        } else {
            holder.address.setVisibility(View.VISIBLE);
            holder.address.setText(rows.getAddress());
        }

        if (rows.getCourseInfo() !=null){
            holder.lin_isShowWeb.setVisibility(View.VISIBLE);
            GlideUtil.load(mContext,rows.getCourseInfo().getCover(),holder.tv_news_img);
            holder.tv_news_title.setText(SubStringUtil.subStringCN(rows.getCourseInfo().getName(),30));
            holder.lin_isShowWeb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance().build("/home/homenew")
                            .withString("title", rows.getCourseInfo().getName())
                            .withString("id", rows.getCourseInfo().getId())
                            .navigation();
                }
            });
        }else {
            holder.lin_isShowWeb.setVisibility(View.GONE);
        }
        //holder.zanCount.setText(String.valueOf(rows.getThumbCount()));
        holder.zanCount.setText("不通过");
        //回复
        //holder.commentCount.setText(String.valueOf(rows.getComments().size()));
        holder.commentCount.setText("通过");
        //Glide.with(mContext, rows.getAvatar(), holder.icon);
        RequestOptions   requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.mipmap.ic_default_img)
                .error(R.mipmap.ic_default_img)
                .centerCrop();
        Glide.with(mContext).load(rows.getAvatar()).apply(requestOptions).into(holder.icon);
        if (rows.getThumbList().size() > 0) {
            String s = rows.getThumbList().toString();
            s = s.replaceAll("\\[", "");
            s = s.replaceAll("\\]", "");
            holder.item_tv_thumbs.setText(s);
            holder.item_tv_thumbs.setVisibility(View.VISIBLE);
        } else {
            holder.item_tv_thumbs.setVisibility(View.GONE);
        }
        final List<String> imagesArray = new ArrayList<>();
        if (rows.getFiles() != null) {
            try {
                JSONArray jsonArray = new JSONArray(rows.getFiles());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    imagesArray.add(jsonObject.getString("url"));     //解析获得 url
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        /**
         * 判断是否是自己发布的看看
         */
        if (mUserId.equals(rows.getCreateUserId())){
            holder.tv_delete.setVisibility(View.VISIBLE);
        }else {
            holder.tv_delete.setVisibility(View.INVISIBLE);
        }
        if (imagesArray.toString().contains("mp4")) {
            holder.multiImageView.setVisibility(View.GONE);
            holder.multi_video_framelayout.setVisibility(View.VISIBLE);
            // 加载视频
            holder.multi_video.setUp(imagesArray.get(0));
            holder.multi_video.setMute(true);
            holder.multi_video.setLooping(true);
            LookControlPanel controlPanel = new LookControlPanel(mContext, imagesArray.get(0));
            controlPanel.setHideControlPlane(false);
            holder.multi_video.setControlPanel(controlPanel);
            //设置视频第一帧预览图
            MediaUtils.getImageForVideo(imagesArray.get(0), new MediaUtils.OnLoadVideoImageListener() {
                @Override
                public void onLoadImage(Bitmap bitmap) {
                    if (bitmap != null) {
                        holder.multi_video.setThumbImg(bitmap);
                    }
                }
            });
            //当列表第一条是视频时 自动播放
            if (position == 0) {
                holder.multi_video.start();
            }
        } else {
            holder.multiImageView.setVisibility(View.VISIBLE);
            holder.multi_video_framelayout.setVisibility(View.GONE);
            holder.multiImageView.setList(imagesArray);
        }

        holder.multiImageView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ImageUrl imageUrl = new ImageUrl();
                imageUrl.setUrlList(imagesArray);
                Gson gson = new Gson();
                String url = gson.toJson(imageUrl);
                Intent intent = new Intent(mContext, LookBigImagesActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("position", position);
                mContext.startActivity(intent);
//                ARouter.getInstance().build("/look/images").withString("url", url)
//                        .withInt("position", position)
//                        .navigation();
            }
        });
        //第一级的时候会有评论的回复内容，需展示
        // final List<LookListBean.Rows.Comments> replays = rows.getComments();
        holder.content.setText(rows.getContent());
        if (rows.getThumbIdList().size() > 0 && rows.getComments().size() > 0) {
            holder.item_line.setVisibility(View.VISIBLE);
        } else {
            holder.item_line.setVisibility(View.GONE);
        }
        if (rows.getComments() != null && rows.getComments().size() > 0) {
            if (holder.lin_comment_comment.getChildCount() > 0) {
                holder.lin_comment_comment.removeAllViews();
            }

            if (holder.lin_comment_reply.getChildCount() > 0) {
                holder.lin_comment_reply.removeAllViews();
            }
            for (int i = 0; i < rows.getComments().size(); i++) {
                holder.lin_comment_replys.setVisibility(View.VISIBLE);
                if (rows.getComments().get(i).getType() == 1) {
                    final LookListBean.Rows.Comments comments = rows.getComments().get(i);
                    CommentTextView commentTextView = new CommentTextView(mContext);
                    LinearLayout.LayoutParams paramses = (LinearLayout.LayoutParams) holder.lin_comment_comment.getLayoutParams();
                    paramses.weight = WindowManager.LayoutParams.MATCH_PARENT;
                    paramses.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    commentTextView.setLayoutParams(paramses);

                    //在小米上长按会闪退 此处消费掉当前textView的长按事件
                    commentTextView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            return true;
                        }
                    });
                    commentTextView.setReply(rows.getComments().get(i), null);
                    commentTextView.setListener(new TextBlankClickListener() {
                        @Override
                        public void onBlankClick(View view) {
                            //ToastUtil.show("" + comments.getContent() + "   " + comments.getFromName() + "   toName=" + comments.getToName());
                            if (mOnActionListener != null) {
                                mOnActionListener.onDetailClick(comments, rows, position);
                            }
                        }

                        @Override
                        public void onLongClick(View view) {
                            //showCoverDialog(rows,"", 0,"回复");
                        }
                    });
                    holder.lin_comment_comment.addView(commentTextView);
                    //holder.tv_comment_test.setReply(replays.get(i));
                } else if (rows.getComments().get(i).getType() == 0) {

                    final LookListBean.Rows.Comments comments = rows.getComments().get(i);
                    CommentTextView commentTextView = new CommentTextView(mContext);
                    LinearLayout.LayoutParams paramses = (LinearLayout.LayoutParams) holder.lin_comment_comment.getLayoutParams();
                    paramses.weight = WindowManager.LayoutParams.MATCH_PARENT;
                    paramses.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    commentTextView.setLayoutParams(paramses);
                    //在小米上长按会闪退 此处消费掉当前textView的长按事件
                    commentTextView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            return true;
                        }
                    });
                    commentTextView.setReply(rows.getComments().get(i), null);
                    commentTextView.setListener(new TextBlankClickListener() {
                        @Override
                        public void onBlankClick(View view) {
                            //    ToastUtil.show("" + comments.getContent() + "   " + comments.getFromName() + "   toName=" + comments.getToName());
                            if (mOnActionListener != null) {
                                mOnActionListener.onDetailClick(comments, rows, position);
                            }
                        }

                        @Override
                        public void onLongClick(View view) {
                            // showCoverDialog(rows,"", 0,"评论");
                        }
                    });
                    holder.lin_comment_reply.addView(commentTextView);
                    // holder.tv_comment_reply.setReply(replays.get(i));
                }

            }
        } else {
            holder.lin_comment_replys.setVisibility(View.GONE);
        }

    }

    private void showCoverDialog(final LookListBean.Rows item, final String id, final int position, String type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("是否要删除此" + type + "？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (mOnActionListener != null) {
                    mOnActionListener.onDeleteCommentsReplsys(item, id, position);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.show();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        OvalImageView icon;
        TextView name;
        TextView time;
        TextView tv_delete;
        TextView tv_news_title;
        TextView item_tv_thumbs;
        TextView commentCount, zanCount;
        TextView content;
        View item_line;
        LinearLayout item_thumbs_lin;
        TextView contentReply;
        TextView address;
        MultiImageView multiImageView;
        View view;
        RecyclerView recyclerView;
        LinearLayout lin_comment_comment;
        LinearLayout lin_comment_reply;
        LinearLayout lin_comment_replys;
        LinearLayout lin_isShowWeb;
        VideoView multi_video;
        ImageView tv_news_img;
        FrameLayout multi_video_framelayout;

        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            icon = itemView.findViewById(R.id.item_icon);
            name = itemView.findViewById(R.id.item_name);
            time = itemView.findViewById(R.id.item_time);
            address = itemView.findViewById(R.id.tv_address);
            tv_delete = itemView.findViewById(R.id.tv_delete);
            tv_news_img = itemView.findViewById(R.id.tv_news_img);
            tv_news_title = itemView.findViewById(R.id.tv_news_title);
            multi_video_framelayout = itemView.findViewById(R.id.multi_video_framelayout);
            multi_video = itemView.findViewById(R.id.multi_video);
            recyclerView = itemView.findViewById(R.id.recycler_iamges);
            commentCount = itemView.findViewById(R.id.item_comment);
            item_thumbs_lin = itemView.findViewById(R.id.item_thumbs_lin);
            item_line = itemView.findViewById(R.id.item_line);
            zanCount = itemView.findViewById(R.id.item_zan);
            item_tv_thumbs = itemView.findViewById(R.id.item_tv_thumbs);
            content = itemView.findViewById(R.id.item_content);
            multiImageView = itemView.findViewById(R.id.multi_image);
            contentReply = itemView.findViewById(R.id.item_content_reply);
            lin_comment_comment = (LinearLayout) itemView.findViewById(R.id.lin_comment_comment);
            lin_comment_reply = (LinearLayout) itemView.findViewById(R.id.lin_comment_reply);
            lin_comment_replys = (LinearLayout) itemView.findViewById(R.id.lin_comment_replys);
            lin_isShowWeb = (LinearLayout) itemView.findViewById(R.id.lin_isShowWeb);
        }

    }

    public interface OnActionListener {
        void onComment(LookListBean.Rows item, int position);

        void onHit(LookListBean.Rows item, int position);

        void onDetailClick(LookListBean.Rows.Comments comments, LookListBean.Rows rows, int position);

        void onAllReplyOpen(LookListBean.Rows item);

        void onDeleteCommentsReplsys(LookListBean.Rows item, String id, int position);

        void onUserIconClick(String userName);

        void onLongClick(LookListBean.Rows item);

        void onDeleteLookClick(String id, int position);
    }
}
